﻿Imports LinhKienMayTinh.CommonMethods

Public Class ProductEdit
    Inherits BasePage

#Region "Khai báo các biến toàn cục"

    Protected Const VIEW_MODE As String = "VIEW_MODE"
    Private Const PRODUCT_CODE As String = "PRODUCT_CODE"

#End Region

#Region "Khai báo các event"

    ''' <summary>
    ''' ProductEdit_Load
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ProductEdit_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim productCode As Integer        

        Try
            If Not IsPostBack Then                

                '' nếu có querystring thì là mode update, ngược lại thì là mode tạo mới
                If IsNothing(Request.QueryString("productcode")) Then                    
                    ViewState(VIEW_MODE) = 1
                Else                    
                    ViewState(VIEW_MODE) = 0
                    productCode = CInt(Request.QueryString("productcode"))
                    ViewState(PRODUCT_CODE) = productCode
                End If

                If ViewState(VIEW_MODE) = 1 Then
                    Call ChangeFormMode(ViewState(VIEW_MODE))
                Else
                    Call SetFormData()
                End If

            End If

        Catch ex As Exception

        End Try
    End Sub

    ''' <summary>
    ''' ProductEdit_Init
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub ProductEdit_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        Try
            Dim master As AdminMasterPage = DirectCast(Me.Page.Master, AdminMasterPage)
            ''add link css
            master.CssLinkAdd(ResolveUrl("~/Style/ProductEditStyle.css"))
            ''add script tool quan ly file
            master.ScriptLinkAdd(ResolveUrl("~/ckfinder/ckfinder.js"))
            master.ScriptLinkAdd(ResolveUrl("~/Scripts/ProductEdit.js"))

            '' binding data cho comnbobox
            Call SetComboboxItem()
        Catch ex As Exception
            Server.Transfer("~/Pages/Error.aspx")
        End Try
    End Sub

    ''' <summary>
    ''' FucntionExec
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub FucntionExec(ByVal sender As Object, ByVal e As System.EventArgs) _
                                                Handles btnEdit.Click,
                                                        btnSave.Click,
                                                        btnDelete.Click,
                                                        btnCancel.Click,
                                                        btnAdd.Click,
                                                        btnRestore.Click

        Dim control As Button = DirectCast(sender, Button)

        Try
            Select Case control.ID
                Case btnEdit.ID     '' button edit
                    ViewState(VIEW_MODE) = 2
                    Call SetFormData()
                Case btnSave.ID     '' button save
                    Call UpdateData()
                Case btnDelete.ID   '' button delete
                    Call DeleteData()
                Case btnCancel.ID   '' button cancel
                    If ViewState(VIEW_MODE) = 1 Then
                        Call ClearError()
                        Call ClearControl()
                    Else
                        ViewState(VIEW_MODE) = 0
                        Call SetFormData()
                    End If
                Case btnAdd.ID      '' button tạo mới
                    Response.Redirect("~/Admin/productedit.aspx")

                Case btnRestore.ID  '' button khôi phục
                    Call RestoreData()

            End Select

        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' add thêm item 0 cho combobox
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Combobox_DataBound(sender As Object, e As System.EventArgs) _
                Handles cbCategory.DataBound,
                        cbManufactory.DataBound

        Dim control As DropDownList = DirectCast(sender, DropDownList)
        Try
            Select Case control.ID
                Case cbCategory.ID
                    cbCategory.Items.Insert(0, New ListItem("--Chọn một--", 0))
                Case cbManufactory.ID
                    cbManufactory.Items.Insert(0, New ListItem("--Chọn một--", 0))
            End Select
        Catch ex As Exception
            Throw
        End Try
    End Sub

#End Region

#Region "Khai báo các function method"

    ''' <summary>
    ''' UpdateData
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub UpdateData()
        Dim xSql As String
        Dim da As DBAccess
        Dim ds As DataSet

        Try
            da = GetDBAccess()

            '' nếu có lỗi input thì không làm gì cả.
            If CheckFormError() = False Then
                Exit Sub
            End If
            '' get cau sql
            If ViewState(VIEW_MODE) = 1 Then
                xSql = CreateInsertSql()
                ds = da.GetDBDataset(xSql)
                ViewState(PRODUCT_CODE) = Nz(ds.Tables(0).Rows(0)("ID"), 0)
            Else
                xSql = CreateUpdateSql()
                da.ExecuteSqlString(xSql)
            End If

            '' sau khi update data thì trở về mode tham chiếu
            ViewState(VIEW_MODE) = 0
            Call SetFormData()

            Response.Write("<script type='text/javascript'>alert('Sản phẩm đã được save thành công.');</script>")
        Catch ex As Exception
            Response.Write("<script type='text/javascript'>alert('Đã xảy ra lỗi trong quá trình lưu sản phẩm. Xin hãy thử lại!');</script>")
        End Try

    End Sub

    ''' <summary>
    ''' delete sản phẩm
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub DeleteData()
        Dim xSql As String
        Dim da As DBAccess

        Try
            da = GetDBAccess()

            xSql = CreateDeleteSql()

            da.ExecuteSqlString(xSql)

            ViewState(VIEW_MODE) = 0
            Call SetFormData()

            Response.Write("<script type='text/javascript'>alert('Đã delete sản phẩm thành công.');</script>")
        Catch ex As Exception            
            Response.Write("<script type='text/javascript'>alert('Đã có lỗi khi delete sản phẩm. Xin hãy thử lại!');</script>")
        End Try


    End Sub

    ''' <summary>
    ''' khôi phục sản phẩm đã delete
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub RestoreData()
        Dim da As DBAccess
        Dim nCode As Integer
        Dim xSql As String

        Try
            da = GetDBAccess()

            nCode = CInt(ViewState(PRODUCT_CODE))
            xSql = "UPDATE T_PRODUCT SET DEL_FLG = 0 WHERE CODE = " & ToSqlStr(nCode, SqlDataType.DataType_Integer)

            da.ExecuteSqlString(xSql)

            ViewState(VIEW_MODE) = 0
            Call SetFormData()

        Catch ex As Exception

        End Try

    End Sub

    ''' <summary>
    ''' GetProduct
    ''' </summary>
    ''' <param name="pCode"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function GetProduct(pCode As Integer) As DataSet
        Dim xSql As String
        Dim dataAccess As DBAccess
        Dim ds As DataSet

        Try
            dataAccess = GetDBAccess()

            xSql = "SELECT * FROM T_PRODUCT WHERE CODE = " & CommonMethods.ToSqlStr(pCode, CommonMethods.SqlDataType.DataType_Integer)

            ds = dataAccess.GetDBDataset(xSql)
            If ds.Tables(0).Rows.Count < 1 Then
                ds = Nothing
            End If

            Return ds

        Catch ex As Exception
            Throw
        End Try
    End Function

    ''' <summary>
    ''' set data cho form
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub SetFormData()

        Dim dsProduct As DataSet        
        Dim nCode As Integer

        Try
            '' clear tất cả các control
            Call ClearControl()
            Call ClearError()

            '' get data
            nCode = CInt(ViewState(PRODUCT_CODE))
            dsProduct = GetProduct(nCode)

            '' nếu data không tồn tại thì thay đổi mode thành tạo mới
            If IsNothing(dsProduct) = True Then
                ViewState(VIEW_MODE) = 1
                Call ChangeFormMode(ViewState(VIEW_MODE))
                Exit Sub
            End If

            '' set data cho các control
            With dsProduct.Tables(0).Rows(0)
                '' CODE
                ViewState(PRODUCT_CODE) = fToInt(.Item("CODE"))
                txtCode.Text = fToText(.Item("CODE"))

                '' NAME
                txtName.Text = fToText(.Item("NAME"))

                '' Image link
                txtFilePath.Text = fToText(.Item("IMG_LINK"))

                '' giá
                If ViewState(VIEW_MODE) = 0 Then
                    txtPrice.Text = Replace(Format(CDbl(fToText(.Item("PRICE"))), "#,##0"), ",", ".")
                Else
                    txtPrice.Text = fToText(.Item("PRICE"))
                End If

                '' tình trạng
                txtCondition.Text = fToText(.Item("CONDITION"))

                '' bảo hành
                txtWarranty.Text = fToText(.Item("WARRANTY"))

                '' nếu là mode tham chiếu thì set cho các control literal
                If ViewState(VIEW_MODE) = 0 Then
                    ltSpec.Text = fToText(.Item("SPECIFICATION"))
                    ltDescription.Text = fToText(.Item("DESCRIPTION"))
                Else '' ngược lại thì set cho các control html editor
                    txtSpec.Text = fToText(.Item("SPECIFICATION"))
                    txtDescription.Text = fToText(.Item("DESCRIPTION"))
                End If
                '' category
                cbCategory.SelectedValue = fToText(.Item("CATEGORY"))

                '' nhà sản xuất
                cbManufactory.SelectedValue = fToText(.Item("MANUFACTORY"))

                '' trạng thái delete
                lbDel.Text = IIf(CInt(.Item("DEL_FLG")) = 0, "", "Đã delete")

                chkHome.Checked = IIf(Nz(.Item("HOME_PAGE_SHOW"), 0) = 0, False, True)

                chkBestSeller.Checked = IIf(Nz(.Item("BEST_SELLER"), 0) = 0, False, True)
            End With

            '' thay đổi form mode
            Call ChangeFormMode(ViewState(VIEW_MODE))
        Catch ex As Exception
            Throw
        End Try

    End Sub

    ''' <summary>
    ''' ChangeFormMode
    ''' </summary>
    ''' <param name="pMode"></param>
    ''' <remarks></remarks>
    Protected Overridable Sub ChangeFormMode(pMode As Integer)

        Select Case pMode
            Case 0      '' mode tham chiếu
                txtName.Enabled = False
                txtPrice.Enabled = False
                txtCondition.Enabled = False
                txtWarranty.Enabled = False
                cbCategory.Enabled = False
                cbManufactory.Enabled = False
                chkHome.Enabled = False
                chkBestSeller.Enabled = False
                txtFilePath.Enabled = False
                btnBrowse.Enabled = False
                btnEdit.Enabled = True
                btnSave.Enabled = False
                btnCancel.Enabled = False
                btnDelete.Enabled = True
                btnAdd.Enabled = True
            Case 1      '' mode tạo mới
                txtName.Enabled = True
                txtPrice.Enabled = True
                txtCondition.Enabled = True
                txtWarranty.Enabled = True
                cbCategory.Enabled = True
                cbManufactory.Enabled = True
                chkHome.Enabled = True
                chkBestSeller.Enabled = True
                txtFilePath.Enabled = True
                btnBrowse.Enabled = True
                btnEdit.Enabled = False
                btnSave.Enabled = True
                btnCancel.Enabled = True
                btnDelete.Enabled = False
                btnAdd.Enabled = False
            Case 2      '' mode update      
                txtName.Enabled = True
                txtPrice.Enabled = True
                txtCondition.Enabled = True
                txtWarranty.Enabled = True
                cbCategory.Enabled = True
                cbManufactory.Enabled = True
                chkHome.Enabled = True
                chkBestSeller.Enabled = True
                txtFilePath.Enabled = True
                btnBrowse.Enabled = True
                btnEdit.Enabled = False
                btnSave.Enabled = True
                btnCancel.Enabled = True
                btnDelete.Enabled = True
                btnAdd.Enabled = False
        End Select

        If lbDel.Text.Length = 0 Then
            btnRestore.Visible = False
            If ViewState(VIEW_MODE) <> 1 Then
                btnDelete.Enabled = True
            End If
        Else
            btnRestore.Visible = True
            btnDelete.Enabled = False
        End If
    End Sub

    ''' <summary>
    ''' set datasource cho cac combobox
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub SetComboboxItem()
        '' combobox category
        With cbCategory
            .DataSource = GetCategoryList().Tables(0)
            .DataValueField = "CODE"
            .DataTextField = "NAME"
        End With

        '' combobox nhà sản xuất
        With cbManufactory
            .DataSource = GetManufactoryList().Tables(0)
            .DataValueField = "CODE"
            .DataTextField = "NAME"
        End With

        Me.DataBind()

    End Sub

    ''' <summary>
    ''' get danh sach category
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function GetCategoryList() As DataSet

        Dim xSql As String
        Dim ds As DataSet
        Dim dataAccess As DBAccess

        Try
            dataAccess = Me.GetDBAccess()

            xSql = "SELECT CODE, NAME FROM T_CATEGORY"

            ds = dataAccess.GetDBDataset(xSql)

            Return ds

        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' get danh sach manufactory
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function GetManufactoryList() As DataSet

        Dim xSql As String
        Dim ds As DataSet
        Dim dataAccess As DBAccess

        Try
            dataAccess = Me.GetDBAccess()

            xSql = "SELECT CODE, NAME FROM T_MANUFACTORY"

            ds = dataAccess.GetDBDataset(xSql)

            Return ds

        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' check lỗi
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CheckFormError() As Boolean

        Dim bNoError As Boolean = True

        Call ClearError()

        If txtName.Text.Length < 1 Then
            lbErrorName.Text = "*Tên sản phẩm không được phép rỗng."
            bNoError = False
        End If

        If cbCategory.SelectedIndex < 1 Then
            lbErrorCategory.Text = "*Phải chọn 1 category."
            bNoError = False
        End If

        If cbManufactory.SelectedIndex < 1 Then
            lbErrorManufactory.Text = "*Phải chọn 1 nhà sản xuất."
            bNoError = False
        End If

        Return bNoError

    End Function

    ''' <summary>
    ''' clear error message
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub ClearError()

        lbErrorName.Text = String.Empty
        lbErrorCategory.Text = String.Empty
        lbErrorManufactory.Text = String.Empty

    End Sub

    ''' <summary>
    ''' ClearControl
    ''' </summary>
    ''' <remarks></remarks>
    Protected Overridable Sub ClearControl()

        txtCode.Text = String.Empty
        txtName.Text = String.Empty
        cbCategory.SelectedIndex = 0
        cbManufactory.SelectedIndex = 0
        txtPrice.Text = String.Empty
        txtFilePath.Text = String.Empty
        txtCondition.Text = String.Empty
        txtWarranty.Text = String.Empty
        txtSpec.Text = String.Empty
        txtDescription.Text = String.Empty        

    End Sub

    ''' <summary>
    ''' tạo câu sql Insert
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateInsertSql() As String
        Dim xSql As String        
        Dim xProductName As String
        Dim xLinkName As String

        Try            
            xProductName = txtName.Text.Trim()
            xLinkName = TrimAccentedString(xProductName)
            xLinkName = TrimNonAlphaNumeric(xLinkName)
            xLinkName = TrimMultiWhiteSpace(xLinkName)
            xLinkName = xLinkName.Trim().ToLower()
            xLinkName = Replace(xLinkName, " ", "-")

            xSql = "BEGIN"
            xSql = xSql & vbCrLf & "INSERT INTO T_PRODUCT("            
            xSql = xSql & vbCrLf & "NAME"
            xSql = xSql & vbCrLf & ",LINK_NAME"
            xSql = xSql & vbCrLf & ",IMG_LINK"
            xSql = xSql & vbCrLf & ",CATEGORY"
            xSql = xSql & vbCrLf & ",MANUFACTORY"
            xSql = xSql & vbCrLf & ",PRICE"
            xSql = xSql & vbCrLf & ",CONDITION"
            xSql = xSql & vbCrLf & ",WARRANTY"
            xSql = xSql & vbCrLf & ",SPECIFICATION"
            xSql = xSql & vbCrLf & ",DESCRIPTION"
            xSql = xSql & vbCrLf & ",HOME_PAGE_SHOW"
            xSql = xSql & vbCrLf & ",BEST_SELLER"
            xSql = xSql & vbCrLf & ") VALUES("            

            '' NAME
            xSql = xSql & vbCrLf & ToSqlStr(xProductName, SqlDataType.DataType_String)

            '' LINK_NAME
            xSql = xSql & vbCrLf & "," & ToSqlStr(xLinkName, SqlDataType.DataType_String)

            '' IMG_LINK
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtFilePath.Text, SqlDataType.DataType_String)

            '' Category
            xSql = xSql & vbCrLf & "," & ToSqlStr(cbCategory.SelectedValue, SqlDataType.DataType_Integer)

            '' Manufactory
            xSql = xSql & vbCrLf & "," & ToSqlStr(cbManufactory.SelectedValue, SqlDataType.DataType_Integer)

            '' Price
            If txtPrice.Text.Length = 0 Then
                xSql = xSql & vbCrLf & ",0"
            Else
                xSql = xSql & vbCrLf & "," & ToSqlStr(txtPrice.Text, SqlDataType.DataType_Integer)
            End If

            '' Condition
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtCondition.Text, SqlDataType.DataType_String)

            '' Warranty
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtWarranty.Text, SqlDataType.DataType_String)

            '' Specification
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtSpec.Text, SqlDataType.DataType_String)

            '' Description
            xSql = xSql & vbCrLf & "," & ToSqlStr(txtDescription.Text, SqlDataType.DataType_String)

            '' Home page show
            If chkHome.Checked = True Then
                xSql = xSql & vbCrLf & "," & ToSqlStr(1, SqlDataType.DataType_Integer)
            Else
                xSql = xSql & vbCrLf & "," & ToSqlStr(0, SqlDataType.DataType_Integer)
            End If

            '' Best seller
            If chkBestSeller.Checked = True Then
                xSql = xSql & vbCrLf & "," & ToSqlStr(1, SqlDataType.DataType_Integer)
            Else
                xSql = xSql & vbCrLf & "," & ToSqlStr(0, SqlDataType.DataType_Integer)
            End If

            xSql = xSql & vbCrLf & ");"

            xSql = xSql & vbCrLf & "SELECT SCOPE_IDENTITY() AS ID;"

            xSql = xSql & vbCrLf & "END"

            Return xSql

        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' CreateUpdateSql
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateUpdateSql() As String
        Dim xSql As String        
        Dim xProductName As String
        Dim xLinkName As String

        Try
            xProductName = txtName.Text.Trim()
            xLinkName = TrimAccentedString(xProductName)
            xLinkName = TrimNonAlphaNumeric(xLinkName)
            xLinkName = TrimMultiWhiteSpace(xLinkName)
            xLinkName = xLinkName.Trim().ToLower()
            xLinkName = Replace(xLinkName, " ", "-")

            xSql = "UPDATE T_PRODUCT SET"
            xSql = xSql & vbCrLf & "NAME = " & ToSqlStr(xProductName, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",LINK_NAME = " & ToSqlStr(xLinkName, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",IMG_LINK = " & ToSqlStr(txtFilePath.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",CATEGORY = " & ToSqlStr(cbCategory.SelectedValue, SqlDataType.DataType_Integer)
            xSql = xSql & vbCrLf & ",MANUFACTORY = " & ToSqlStr(cbManufactory.SelectedValue, SqlDataType.DataType_Integer)
            xSql = xSql & vbCrLf & ",PRICE = " & ToSqlStr(txtPrice.Text, SqlDataType.DataType_Integer)
            xSql = xSql & vbCrLf & ",CONDITION = " & ToSqlStr(txtCondition.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",WARRANTY = " & ToSqlStr(txtWarranty.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",SPECIFICATION = " & ToSqlStr(txtSpec.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",DESCRIPTION = " & ToSqlStr(txtDescription.Text, SqlDataType.DataType_String)
            xSql = xSql & vbCrLf & ",HOME_PAGE_SHOW = " & ToSqlStr(IIf(chkHome.Checked = True, 1, 0), SqlDataType.DataType_Integer)
            xSql = xSql & vbCrLf & ",BEST_SELLER = " & ToSqlStr(IIf(chkBestSeller.Checked = True, 1, 0), SqlDataType.DataType_Integer)
            xSql = xSql & vbCrLf & "WHERE"
            xSql = xSql & vbCrLf & "CODE = " & ToSqlStr(ViewState(PRODUCT_CODE), SqlDataType.DataType_Integer)

            Return xSql
        Catch ex As Exception
            Throw
        End Try

    End Function

    ''' <summary>
    ''' CreateDeleteSql
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Protected Overridable Function CreateDeleteSql() As String
        Dim xSql As String

        Try
            xSql = "UPDATE T_PRODUCT SET DEL_FLG = 1 WHERE CODE = " & ToSqlStr(ViewState(PRODUCT_CODE), SqlDataType.DataType_Integer)

            Return xSql
        Catch ex As Exception
            Throw
        End Try

    End Function

#End Region

End Class